package com.example.myesptest;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;

import com.example.myesptest.RockView.RockerView;
import com.example.myesptest.RockView.SeekBarVertical;
import com.example.myesptest.myudp.UDPBuild;

import java.util.Arrays;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MainActivity extends AppCompatActivity {

    private static final int POOL_SIZE = 2;
    private static final String TAG = MainActivity.class.getSimpleName();
    AppCompatActivity mActivity;
    private MjpegView view1;
    private UDPBuild udpBuild;
    private ExecutorService mThreadPool;
    private Thread mThread;
    byte[] buf = {0x52, 0x00, 0x00, 0x00, 0x55};
    byte[] lastBuf = {0x52, 0x00, 0x00, 0x00, 0x55};

    private String getMethodName() {
        StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
        StackTraceElement e = stacktrace[3];
        return e.getMethodName();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mActivity = this;
        view1 = findViewById(R.id.mjpegview1);
        view1.setAdjustHeight(true);
        //view.setAdjustWidth(true);
        view1.setMode(MjpegView.MODE_FIT_WIDTH);
        //view.setMsecWaitAfterReadImageError(1000);
        view1.setUrl("http://192.168.4.1:81/stream");
        view1.setRecycleBitmap(true);

        RockerView mRockerView = findViewById(R.id.rocker_view);  // 1
        TextView direction_Text = findViewById(R.id.direction_Text);    // 1当前方向
        TextView angle_Text = findViewById(R.id.angle_Text);   // 1当前角度
        TextView level_Text = findViewById(R.id.level_Text);    // 1当前偏移级别
//        mRockerView.setOnShakeListener(MyRockerView.DirectionMode.DIRECTION_8, new MyRockerView.OnShakeListener() {
//            @Override
//            public void onStart() {
//
//            }
//
//            @Override
//            public void direction(MyRockerView.Direction direction) {
//                String directionXY;
//                switch (direction) {
//                    case DIRECTION_CENTER: {
//                        directionXY = "当前方向：中心";
//                        angle_Text.setText("当前方向：");
//                        level_Text.setText("当前偏移级别：");
//                        break;
//                    }
//                    case DIRECTION_DOWN: {
//                        directionXY = "当前方向：下";
//                        break;
//                    }
//                    case DIRECTION_LEFT: {
//                        directionXY = "当前方向：左";
//                        break;
//                    }
//                    case DIRECTION_UP: {
//                        directionXY = "当前方向：上";
//                        break;
//                    }
//                    case DIRECTION_RIGHT: {
//                        directionXY = "当前方向：右";
//                        break;
//                    }
//                    case DIRECTION_DOWN_LEFT: {
//                        directionXY = "当前方向：左下";
//                        break;
//                    }
//                    case DIRECTION_DOWN_RIGHT: {
//                        directionXY = "当前方向：右下";
//                        break;
//                    }
//                    case DIRECTION_UP_LEFT: {
//                        directionXY = "当前方向：左上";
//                        break;
//                    }
//                    case DIRECTION_UP_RIGHT: {
//                        directionXY = "当前方向：右上";
//                        break;
//                    }
//                    default:
//                        throw new IllegalStateException("Unexpected value: " + direction);
//                }
//                Log.e(TAG, "XY轴" + directionXY);
//                Log.e(TAG, "-----------------------------------------------");
//                direction_Text.setText(directionXY);
//            }
//
//            @Override
//            public void onFinish() {
//
//            }
//        });

//        mRockerView.setOnAngleChangeListener(new RockerView.OnAngleChangeListener() {
//            @Override
//            public void onStart() {
//
//            }
//
//            @Override
//            public void angle(double angle) {
//                String angleXY;
//                angleXY = "当前角度：" + angle;
//                Log.e(TAG, "XY轴" + angleXY);
//                angle_Text.setText(angleXY);
//            }
//
//            @Override
//            public void onFinish() {
//
//            }
//        });

//        mRockerView.setOnDistanceLevelListener(level -> {
//            String levelXY;
//            levelXY = "当前距离级别：" + level;
//            Log.e(TAG, "XY轴" + levelXY);
//            level_Text.setText(levelXY);
//        });

        mRockerView.setOnShakeAngleDistanceLevelListener(new RockerView.OnShakeAngleDistanceLevelListener() {
            @Override
            public void onStart() {

            }

            @Override
            public void onShakeAngleDistanceLevel(RockerView.Direction direction, double angle, int level) {
                Log.e(TAG, "test:" + direction + " 当前角度：" + angle + " 当前距离级别：" + level);
                buf[0] = 0x52;
                if (angle < 50) {
                    buf[1] = 40;
                } else if (angle < 130) {
                    buf[1] = (byte) (90 - angle);
                } else if (angle < 230) {
                    buf[1] = -40;
                } else if (angle < 310) {
                    buf[1] = (byte) (angle - 270);
                } else {
                    buf[1] = 40;
                }
                if (angle > 180) {
                    buf[2] = 0;
                } else {
                    buf[2] = (byte) 0x80;
                }
                buf[2] |= level * 10;
            }

            @Override
            public void onFinish() {
                buf[0] = 0x52;
                buf[1] = 0;
                buf[2] = 0;
            }
        });

        udpBuild = UDPBuild.getUdpBuild();
        udpBuild.setUdpReceiveCallback(data -> {
            String strReceive = new String(data.getData(), 0, data.getLength());
//                SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
//                Date curDate =  new Date(System.currentTimeMillis());
//                String str = formatter.format(curDate);
//                String str = SimpleDateFormat.getDateTimeInstance().format(System.currentTimeMillis());
//                TextView receive = findViewById(R.id.receive_textView);
//                receive.append(str + ':' + strReceive + '\n');
            Log.d(TAG, "OnParserComplete: " + strReceive);
        });

        int cpuNumbers = Runtime.getRuntime().availableProcessors();
        mThreadPool = Executors.newFixedThreadPool(cpuNumbers * POOL_SIZE);
        udpBuild.sendRAMDate(buf, buf.length);
        Log.d(TAG, "sendRAMDate: " + buf.length);
//        mThreadPool.execute(() -> {
//            while (true) {
//                if (!Arrays.equals(buf, lastBuf)) {
//                    System.arraycopy(buf, 0, lastBuf, 0, buf.length);
//                    udpBuild.sendRAMDate(lastBuf, lastBuf.length);
//                    Log.d(TAG, "sendRAMDate: " + String.format("%02X %02X %02X %02X", lastBuf[0],lastBuf[1],lastBuf[2],lastBuf[3]));
//                }
//                SystemClock.sleep(50);
//            }
//        });
        mThread = new Thread(() -> {
            while (true) {
                if (!Arrays.equals(buf, lastBuf)) {
                    System.arraycopy(buf, 0, lastBuf, 0, buf.length);
                    udpBuild.sendRAMDate(lastBuf, lastBuf.length);
                    Log.d(TAG, "sendRAMDate: " + String.format("%02X %02X %02X %02X", lastBuf[0], lastBuf[1], lastBuf[2], lastBuf[3]));
                }
                SystemClock.sleep(50);
            }
        });
        mThread.setPriority(10);
        mThread.start();

        SeekBarVertical sbv = findViewById(R.id.seek_view);
        sbv.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                Log.d(TAG, "onProgressChanged: " + i);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    public void onClickStartHome(View view) {
        Log.d(TAG, getMethodName() + "--> IN");

        Intent mHomeIntent = new Intent(Intent.ACTION_MAIN);

        mHomeIntent.addCategory(Intent.CATEGORY_HOME);
        mHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
        startActivity(mHomeIntent);

        Log.d(TAG, getMethodName() + "--> OUT");
    }

    @Override
    protected void onResume() {
        view1.startStream();
        super.onResume();
    }

    @Override
    protected void onPause() {
        view1.stopStream();
        super.onPause();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return false;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onStop() {
        view1.stopStream();
        super.onStop();
    }
}
